<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
import 'echarts/map/js/china.js'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
import { ceilNumber } from '@/utils'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '400px'
    },
    chartData: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      if (!this._.isEmpty(this.chartData)) {
        this.setOptions(this.chartData)
      }
    },
    setOptions(chartData) {
      const maxVal = this._.maxBy(chartData, 'value').value
      this.chart.setOption({
        tooltip: {
          trigger: 'item'
        },
        visualMap: {
          type: 'piecewise',
          min: 0,
          max: ceilNumber(maxVal),
          color: ['#ec7644', '#f5efeb']
        },
        series: [{
          type: 'map',
          name: '省份分布',
          map: 'china',
          label: {
            normal: {
              show: false
            },
            emphasis: {
              show: false
            }
          },
          data: chartData
        }]
      })
    }
  }
}
</script>
